package com.example.learndevice.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.os.Looper
import android.util.AttributeSet
import android.util.Log
import android.view.View

/**
 *
 * @Author： LJH
 * @Time： 2022/7/5
 * @description：
 */
class TurnView(context: Context,attributeSet: AttributeSet):View(context,attributeSet) {
    private val mPaint = Paint()
    private lateinit var mRectF:RectF
    private var mBeginAngle = 0
    private var mRunning = false

    private val mHandler = android.os.Handler(Looper.getMainLooper())

    init {
        mPaint.isAntiAlias = true
        mPaint.color = Color.RED
        mPaint.strokeWidth = 10F
        mPaint.style = Paint.Style.FILL
    }

    @SuppressLint("DrawAllocation")
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //直径
        val diameter = measuredWidth - paddingLeft - paddingRight
        mRectF = RectF(paddingLeft.toFloat(),paddingTop.toFloat(),(paddingLeft+diameter).toFloat(),(paddingTop+diameter).toFloat())
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.drawArc(mRectF,mBeginAngle.toFloat(),30F,true,mPaint)
    }

    fun start(){
        mRunning = true
        mHandler.postDelayed(runnable,0)
    }

    fun stop(){
        mRunning = false
    }

    private val runnable = object : Runnable{
        override fun run() {
            if (mRunning){
                Log.d("TurnView",Thread.currentThread().name)
                mHandler.postDelayed(this,70)
                mBeginAngle += 3
                invalidate()
            }else{
                mHandler.removeCallbacks(this)
            }
        }
    }
}